/*
 * Logger.cpp
 *
 *  Created on: 23 mei 2013
 *      Author: maarten
 */

#include <fcntl.h>
#include <ctime>
#include <cstring>
#include <sstream>
#include <iomanip>
#include <unistd.h>
#include <iostream>

#include "Logger.hpp"
//#include "Config.hpp"

#define SLOGFILE "log.txt"

Logger Logger::pLogger;

Logger::Logger() {
	std::stringstream buffer;
	display = true;
	file = true;

	buffer << "NEW SESSON";

	if (file) {
		logfile = open(SLOGFILE, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR);
		if (logfile < 0) {
			file = false;
			log(buffer.str());
			log("FAIL TO OPEN LOGFILE");
		} else {
			log(buffer.str());
		}
	}
}

Logger& Logger::getInstance() {
	return pLogger;
}

void Logger::log(Message aMessage) {
	std::stringstream buffer;

	if (aMessage.getHeader() < 100) {
		buffer << "SEND ";
	} else {
		buffer << "RECV ";
	}

	buffer << "bytes: " << std::setfill('0') << std::setw(4) << aMessage.getCompleteMessageSize() << " : ";

	if (aMessage.getHeader() == RESPONSE_DOWNLOAD_TRANSFER || aMessage.getHeader() == REQUEST_UPLOAD_TRANSFER) {
		buffer << std::setfill('0') << std::setw(3) << aMessage.getHeader() << " : " << "FILE TRANSFER";
	} else {
		buffer << std::setfill('0') << std::setw(3) << aMessage.getHeader() << " : " << aMessage.getBody();
	}

	log(buffer.str());
}

void Logger::log(std::string aString) {
	std::stringstream buffer;
	buffer << getLogTime() << aString << std::endl;

	if (file) {
		write(logfile, buffer.str().c_str(), buffer.str().length());
	}
	if (display) {
		std::cout << buffer.str();
	}
}

std::string Logger::getLogTime() {
	std::stringstream buffer;

	time_t t = time(0);
	struct tm * now = localtime(&t);

	buffer << std::setfill('0') << std::setw(2) << now->tm_hour << ":";
	buffer << std::setfill('0') << std::setw(2) << now->tm_min << ":";
	buffer << std::setfill('0') << std::setw(2) << now->tm_sec << ":";
	buffer << " ";

	return buffer.str();
}

Logger::~Logger() {
	close(logfile);
}
